package com.shaozi.nc.quartz.job;

import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.util.StringUtils;

import com.shaozi.common.schedule.DyncQuartzManage;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.PushMsgModel;
import com.shaozi.nc.data.mongodao.PushMsgMDao;
import com.shaozi.nc.io.mq.PushMsgProducer;
import com.shaozi.utils.common.BeanUtils;
import com.shaozi.utils.common.SysUtils;

public class PushMsgJob implements Job {
	private static final Logger logger = Logger.getLogger(PushMsgJob.class);
	private PushMsgProducer pushProducer;

	public PushMsgJob() {
		pushProducer = new PushMsgProducer();

	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		TriggerKey key = context.getTrigger().getKey();
		String groupId = key.getGroup();
		if (StringUtils.isEmpty(groupId)) {
			logger.debug("get trigger's group null");
			return;
		}
		String compId = groupId.split("_")[0];
		String _id = key.getName();
		if (StringUtils.isEmpty(_id)) {
			logger.debug("get trigger's name null," + compId);
			return;
		}
		PushMsgMDao pushDao = BeanUtils.getBean(PushMsgMDao.class);
		PushMsgModel model = pushDao.getById(compId, _id);
		if (model == null) {
			logger.info("get id null: " + _id);
			removeJob(context);
			return;
		}
		doPush(model);
		Date nextDate = context.getTrigger().getNextFireTime();
		if (nextDate != null) {
			model.setNextPushTime(nextDate.getTime());
			pushDao.save(compId, model);
		} else {
			//得不到下次执行的时间 ，说明已不在执行
			pushDao.removePushMsg(compId, _id);
		}
		if (logger.isInfoEnabled()) {
			logger.info("job=" + _id + ",next fire time:" + SysUtils.formatDate(context.getTrigger().getNextFireTime()));
		}

	}

	private void doPush(PushMsgModel model) {
		pushProducer.pushMsg(model);
	}

	private void removeJob(JobExecutionContext context) {
		DyncQuartzManage mgr = (DyncQuartzManage) BeanUtils.getBean("dyncQuartzMgr");
		JobKey jobKey = context.getJobDetail().getKey();
		TriggerKey key = context.getTrigger().getKey();
		try {
			mgr.removeJob(jobKey, key);
		} catch (SchedulerException e) {
			logger.error(SzException.getStackMessage(e));
		}

	}
}
